<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>系统界面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--    <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css">-->
    <style>

    </style>
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 委托商 -->
        <div class="form-item">
            <label class="form-label">委托商：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入委托商">
        </div>

        <!-- 负责人 -->
        <div class="form-item">
            <label class="form-label">批次号：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入批次号">
        </div>

        <!-- 运输方式 -->
        <div class="form-item">
            <label class="form-label">运输方式：</label>
            <select class="form-input form-select">
                <option value="">全部</option>
                <option value="1">公路</option>
                <option value="2">水路</option>
                <option value="3">水陆联运</option>
            </select>
        </div>
        <div class="form-item">
            <label class="form-label">创建时间：</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="ID-laydate-demo1" placeholder="yyyy-MM-dd">
            </div>
            -
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="ID-laydate-demo2" placeholder="yyyy-MM-dd">
            </div>
        </div>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">

        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>委托商</th>
            <th>批次号</th>
            <th>运输方式</th>
            <th>委托车数量</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- 分页 -->
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option class="" value="10" selected>10条/页</option>
        <option class="" value="20">20条/页</option>
        <option class="" value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>
<div class="modal-mask" id="modal-mask-vehicle-detail">
    <div class="modal-content">
        <h3 class="modal-title">
            运输计划详情
            <button class="modal-close-btn">×</button>
        </h3>
        <div class="modal-body">
            <div class="detail-section">
                <h4 class="detail-subtitle">基础信息</h4>
                <div class="detail-row">
                    <span class="detail-label">委托商：</span>
                    <span id="detail-consignorName" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">批次号：</span>
                    <span id="detail-batchNumber" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">运输方式：</span>
                    <span id="detail-transportMode" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">总数量：</span>
                    <span id="detail-planCount" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">已有数量：</span>
                    <span id="detail-leftoverPlanCount" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">状态：</span>
                    <span id="detail-state" class="detail-value"></span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">创建时间：</span>
                    <span id="detail-createTime" class="detail-value"></span>
                </div>
            </div>

            <div class="detail-section">
                <h4 class="detail-subtitle">委托车辆</h4>
                <div class="vehicle-table-container">
                    <table class="vehicle-table">
                        <thead>
                        <tr>
                            <th>运单号</th>
                            <th>车架号</th>
                            <th>计划时间</th>
                            <th>起始区域</th>
                            <th>起始港</th>
                            <th>交车港</th>
                            <th>交车区域</th>
                            <th>品牌</th>
                            <th>型号</th>
                            <th>状态</th>
                        </tr>
                        </thead>
                        <tbody id="detail-vehicleList"></tbody>
                    </table>
                </div>
            </div>

            <div class="detail-section">
                <h4 class="detail-subtitle">操作记录</h4>
                <div id="detail-operationLogs"></div>
            </div>
        </div>
        <div class="modal-buttons">
            <button type="button" class="btn-close">关闭</button>
        </div>
    </div>
</div>
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content">
        <h3 class="modal-title">
            新增运输计划
            <button class="modal-close-btn">×</button>
        </h3>

        <form class="modal-form" id="modal-form-add">
            <div class="form-item">
                <label>委托商名称：</label>
                <input type="text" name="consignorName"
                       placeholder="请输入委托商名称"
                       required>
                <div class="form-error"></div>
            </div>

            <div class="form-item">
                <label>批次号：</label>
                <input type="text" name="batchNumber"
                       placeholder="请输入批次号"
                       required>
                <div class="form-error"></div>
            </div>

            <div class="form-item">
                <label>运输方式：</label>
                <select name="transportMode" class="form-select" required>
                    <option value="">请选择</option>
                    <option value="1">公路</option>
                    <option value="2">水路</option>
                    <option value="3">水陆联运</option>
                </select>
                <div class="form-error"></div>
            </div>

            <div class="form-item">
                <label>委托车数量：</label>
                <input type="number" name="planCount"
                       placeholder="请输入数量"
                       min="1" required>
                <div class="form-error"></div>
            </div>

            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">提交</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-mask" id="modal-mask-update">
    <div class="modal-content">
        <h3 class="modal-title">
            修改运输计划  <!-- 修改标题 -->
            <button class="modal-close-btn">×</button>
        </h3>

        <form class="modal-form" id="modal-form-update">
            <div class="form-item">
                <label>委托商名称：</label>
                <!-- 修改为运输计划相关字段 -->
                <input type="text" name="consignorName"
                       placeholder="请输入委托商名称"
                       required>
                <div class="form-error"></div>
            </div>

            <div class="form-item">
                <label>批次号：</label>
                <input type="text" name="batchNumber"
                       placeholder="请输入批次号"
                       required>
                <div class="form-error"></div>
            </div>

            <div class="form-item">
                <label>委托车数量：</label>
                <input type="number" name="planCount"
                       placeholder="请输入数量"
                       min="1" required>
                <div class="form-error"></div>
            </div>

            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">修改</button>
            </div>
        </form>
    </div>
</div>
<script>
    const nextButton = document.querySelector('.next-button')
    const preButton = document.querySelector('.pre-button')
    //渲染
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        if (data.data.current >= data.data.pages){
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        }else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1){
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        }else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');

            // 生成表格内容
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.consignorName}</td>
                <td>${item.batchNumber || ''}</td>
                <td>${item.transportMode ===1? "公路" : (item.transportMode ===2 ? "水路":"水路联运")}</td>
                <td>${item.planCount}</td>
               <td>${formatDateTime(item.createTime)}</td>
                <td>
                    <button class="table-detail-btn">详情</button>
<!--                    <button class="table-disable-btn">禁用</button>-->
                    <button class="table-edit-btn">修改</button>
                    <button class="table-delete-btn">删除</button>
                </td>
    `;

            // 绑定操作按钮事件
            // const disableBtn = tr.querySelector('.table-disable-btn');
            const detailBtn = tr.querySelector('.table-detail-btn');
            const editBtn = tr.querySelector('.table-edit-btn');
            const deleteBtn = tr.querySelector('.table-delete-btn');
            // 禁用/启用切换
            // disableBtn.addEventListener('click', () => disableDepartment(item.id, item.status));
            // disableBtn.textContent = item.status === 1 ? '禁用' : '启用';
            detailBtn.addEventListener('click', () => showPlanDetail(item.id));
            // 修改功能
            editBtn.addEventListener('click', () => updateDepartment(item));

            // 删除功能
            deleteBtn.addEventListener('click', () => deleteDepartment(item.id));

            tbody.appendChild(tr);
        });
    }
    document.querySelector('.btn-query').addEventListener('click',function (){
        fetchData('query');
    })
    document.querySelector('.pre-button').addEventListener('click',function (){
        fetchData('pre');
    })
    document.querySelector('.next-button').addEventListener('click',function (){
        fetchData('next');
    })
    // 统一请求方法
    async function fetchData(type) {

        let { page, pageSize } = getPaginationParams();
        if (type === 'pre') {
            page = Math.max(1, page - 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }else if (type === 'next'){
            page = Math.max(1, page + 1)  // 确保页码不小于1
            document.querySelector('.page-num span').textContent = page  // 同步更新页码显示
        }
        const queryParams = {
            consignorName: document.querySelector('input[placeholder="请输入委托商"]').value,
            batchNumber: document.querySelector('input[placeholder="请输入批次号"]').value,
            transportMode: document.querySelector('.form-select').value,
            startTime: document.getElementById('ID-laydate-demo1').value, // 添加创建时间参数
            endTime: document.getElementById('ID-laydate-demo2').value, // 添加创建时间参数
            page: page,
            rows: pageSize
        };

        try {
            const response = await fetch('http://localhost:8080/transportPlan/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
            }else  if (data.status === -1) {
                console.error('请求失败:', error);
            }
        } catch (error) {
            console.error('请求失败:', error);
            renderTable({ data: { records: [], total: 0, current: 1, pages: 0 } });
        }
    }
    //重置按钮
    document.querySelector('.btn-reset').addEventListener('click',()=>{
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '' // 清空文本输入
            if (input.tagName === 'SELECT') input.value = '' // 重置选择框
        });
        // 增加日期控件清空
        document.getElementById('ID-laydate-demo1').value = '';
        document.getElementById('ID-laydate-demo2').value = '';
    })
    //新增按钮相关
    // 显示弹窗
    document.querySelector('.btn-add').addEventListener('click', () => {
        document.querySelector('#modal-mask-add').style.display = 'flex'
    })
    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    document.querySelectorAll('.btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });
    // 表单提交处理
    document.querySelector('#modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault()

        const formData = {
            consignorName: e.target.consignorName.value,
            batchNumber: e.target.batchNumber.value,
            transportMode: parseInt(e.target.transportMode.value),
            planCount: parseInt(e.target.planCount.value)
        }

        // try {
            const response = await fetch('http://localhost:8080/transportPlan/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            })
            const data = await response.json();
            if(data.status===0) {
                // alert("添加成")
                document.querySelector('#modal-mask-add').style.display = 'none'
                fetchData('query') // 刷新表格数据
            }
        // } catch(err) {
        //     console.error('提交失败:', err)
        // }
    })
    //表格函数
    // 新增以下功能函数
    async function deleteDepartment(id) {
        if (!confirm('确定要删除该计划吗？')) return;
        try {
            const res = await fetch(`http://localhost:8080/transportPlan/delete/${id}`, {
                method: 'GET'
            });
            const data = await res.json();

            if(data.status === 0) {
                alert('删除成功');
                fetchData('query');
            }
        } catch(err) {
            console.error('删除失败:', err);
        }
    }
    // 详情弹窗管理
    let currentDetailModal = null;
    async function showPlanDetail(planId) {
        try {
            const modal = document.getElementById('modal-mask-vehicle-detail');
            const res = await fetch(`http://localhost:8080/transportPlan/detail/${planId}`);
            const response = await res.json();

            if (response.status === 0) {
                const data = response.data;

                // 其他信息填充保持不变...
                // 填充基础信息
                document.getElementById('detail-consignorName').textContent = data.consignorName || '--';
                document.getElementById('detail-batchNumber').textContent = data.batchNumber || '--';
                document.getElementById('detail-transportMode').textContent =
                    data.transportMode === 1 ? '公路' :
                        data.transportMode === 2 ? '水路' : '水陆联运';
                document.getElementById('detail-planCount').textContent = data.planCount || '0';
                document.getElementById('detail-leftoverPlanCount').textContent = data.leftoverPlanCount || '0';
                document.getElementById('detail-state').textContent = getPlanStateText(data.state);
                document.getElementById('detail-createTime').textContent =
                    data.createTime ? formatDateTime(data.createTime) : '--';
                // 委托车辆表格渲染
                const vehicleList = data.transportChildCvList || [];
                const vehicleTbody = document.getElementById('detail-vehicleList');

                if (vehicleList.length > 0) {
                    vehicleTbody.innerHTML = vehicleList.map(vehicle => `
                    <tr>
                        <td>${vehicle.waybillNo || '--'}</td>
                        <td>${vehicle.frameNumber || '--'}</td>
                        <td>${vehicle.planDate || '--'}</td>
                        <td>${vehicle.departurePlace || '--'}</td>
                        <td>${vehicle.departurePort || '--'}</td>
                        <td>${vehicle.arrivePort || '--'}</td>
                        <td>${vehicle.departurePortArea || '--'}</td>
                        <td>${vehicle.brandName || '--'}</td>
                        <td>${vehicle.modelName || '--'}</td>
                        <td>${getVehicleStatus(vehicle.state)}</td>
                    </tr>
                `).join('');
                } else {
                    vehicleTbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="no-vehicle">暂无车辆信息</td>
                    </tr>
                `;
                }

                // 操作记录渲染
                const logs = data.operateRecordList || [];
                const logsContainer = document.getElementById('detail-operationLogs');
                if (logs.length > 0) {
                    logsContainer.innerHTML = logs.map(log => `
                    <div class="log-item">
                    <div class="log-time">
                        ${log.createTime ? formatDateTime(log.createTime) : '--'}
                    </div>
                    <div>
                        <span class="log-type ">
                            ${log.operateType || '--'}
                        </span>
                    </div>
                    <div class="log-remark">
                        ${log.remark || '无备注信息'}
                    </div>
                </div>
                `).join('');
                } else {
                    logsContainer.innerHTML = `
                <div class="no-logs">暂无操作记录</div>
            `;
                }


                modal.style.display = 'flex';
                currentDetailModal = modal;
            }
        } catch (err) {
            console.error('详情加载失败:', err);
            alert('详情加载失败');
        }
    }
    // 修改功能弹窗
    let currentEditHandler = null;
    // 修改功能（需要实现编辑弹窗）
    function updateDepartment(item) {
        const form = document.getElementById('modal-form-update');
        const modal = document.querySelector('#modal-mask-update');

        // 清除之前的事件监听器
        if (form._submitHandler) {
            form.removeEventListener('submit', form._submitHandler);
        }

        // 填充表单数据
        form.querySelector('[name="consignorName"]').value = item.consignorName;
        form.querySelector('[name="batchNumber"]').value = item.batchNumber;
        form.querySelector('[name="planCount"]').value = item.planCount;
        form.dataset.id = item.id; // 存储ID用于提交

        // 绑定新的事件处理器
        const submitHandler = async (e) => {
            e.preventDefault();

            const formData = {
                id: item.id,
                consignorName: form.querySelector('[name="consignorName"]').value,
                batchNumber: form.querySelector('[name="batchNumber"]').value,
                planCount: parseInt(form.querySelector('[name="planCount"]').value)
            };

            try {
                const res = await fetch('http://localhost:8080/transportPlan/update', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(formData)
                });

                const data = await res.json();
                if(data.status === 0) {
                    modal.style.display = 'none';
                    fetchData('query'); // 刷新表格
                } else {
                    alert('更新失败: ' + data.msg);
                }
            } catch(err) {
                console.error('更新失败:', err);
                alert('网络请求异常');
            }
        };

        form._submitHandler = submitHandler; // 存储引用用于后续移除
        // 移除旧事件监听器并绑定新的
        form.removeEventListener('submit', submitHandler);
        form.addEventListener('submit', submitHandler);

        modal.style.display = 'flex';
    }

    layui.use(function() {
        var laydate = layui.laydate;
        // 渲染
        laydate.render({
            elem: '#ID-laydate-demo1'
        });
        laydate.render({
            elem: '#ID-laydate-demo2'
        });
    });

    function closeDetailModal() {
        if (currentDetailModal) {
            currentDetailModal.style.display = 'none';
        }
    }

    // 状态转换
    function getPlanStateText(state) {
        const states = {
            0: '待执行',
            1: '执行中',
            2: '已完成',
            '-1': '已取消'
        };
        return states[state] || '未知状态';
    }

    function getVehicleStatus(status) {
        const statusMap = {
            0: '待分配运输',
            1: '已分配运输',
            2: '运输中',
            3: '已交车'
        };
        return statusMap[status] || '未知';
    }

    // 绑定关闭事件
    document.querySelectorAll('#modal-mask-vehicle-detail .modal-close-btn, #modal-mask-vehicle-detail .btn-close').forEach(btn => {
        btn.addEventListener('click', closeDetailModal);
    });
</script>
</body>
</html>